package com.example.oj.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.oj.entity.User;
import com.example.oj.service.UserService;
import com.example.ojcommon.annotation.AuthCheck;
import com.example.ojcommon.common.BaseResponse;
import com.example.ojcommon.common.DeleteRequest;
import com.example.ojcommon.common.ErrorCode;
import com.example.ojcommon.common.ResultUtils;
import com.example.ojcommon.constant.UserConstant;
import com.example.ojcommon.exception.BusinessException;
import com.example.ojcommon.exception.ThrowUtils;
import com.example.oj.entity.dto.user.UserAddRequest;
import com.example.oj.entity.dto.user.UserLoginRequest;
import com.example.oj.entity.dto.user.UserQueryRequest;
import com.example.oj.entity.dto.user.UserUpdateRequest;
import com.example.oj.entity.vo.UserVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Objects;

/**
 * 用户接口
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

  @Resource
  private UserService userService;

  /**
   * 用户注册
   *
   * @param userAddRequest
   * @return
   */
  @PostMapping("/register")
  public BaseResponse<Long> userRegister(@RequestBody UserAddRequest userAddRequest) {
    if (userAddRequest == null) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数错误");
    }
    String nickname = userAddRequest.getNickname();
    String username = userAddRequest.getUsername();
    String password = userAddRequest.getPassword();
    if (StringUtils.isAnyBlank(nickname, username, password)) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数错误");
    }
    long result = userService.userRegister(userAddRequest);
    return ResultUtils.success(result);
  }

  /**
   * 用户登录
   *
   * @param userLoginRequest
   * @param request
   * @return
   */
  @PostMapping("/login")
  public BaseResponse<UserVO> userLogin(@RequestBody UserLoginRequest userLoginRequest,
                                        HttpServletRequest request) {
    if (userLoginRequest == null) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
    }
    String username = userLoginRequest.getUsername();
    String password = userLoginRequest.getPassword();
    if (StringUtils.isAnyBlank(username, password)) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
    }
    UserVO loginUserVO = userService.userLogin(userLoginRequest, request);
    return ResultUtils.success(loginUserVO);
  }

  /**
   * 用户注销
   *
   * @param request
   * @return
   */
  @PostMapping("/logout")
  public BaseResponse<Boolean> userLogout(HttpServletRequest request) {
    if (request == null) {
      throw new BusinessException(ErrorCode.OPERATION_ERROR, "用户退出异常");
    }
    boolean result = userService.userLogout(request);
    return ResultUtils.success(result);
  }

  /**
   * 获取当前登录用户
   *
   * @param request
   * @return
   */
  @GetMapping("/get/login")
  public BaseResponse<UserVO> getLoginUser(HttpServletRequest request) {
    User user = userService.getLoginUser(request);
    if(Objects.isNull(user)){
      throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
    }
    return ResultUtils.success(userService.getUserVO(user));
  }

  /**
   * 删除用户
   *
   * @param deleteRequest
   * @param request
   * @return
   */
  @PostMapping("/delete")
  @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
  public BaseResponse<Boolean> deleteUser(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
    if (deleteRequest == null || deleteRequest.getId() == null) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR, "删除用户异常");
    }
    boolean b = userService.removeById(deleteRequest.getId());
    return ResultUtils.success(b);
  }

  /**
   * 更新用户
   *
   * @param userUpdateRequest
   * @param request
   * @return
   */
  @PostMapping("/update")
  public BaseResponse<Integer> updateUser(@RequestBody UserUpdateRequest userUpdateRequest,
                                          HttpServletRequest request) {
    if (userUpdateRequest == null || userUpdateRequest.getId() == null) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR, "更新用户异常");
    }
    Integer Integer = userService.updateUser(userUpdateRequest);
    return ResultUtils.success(Integer);
  }

  /**
   * 更新头像
   *
   * @param request
   * @return
   */
  @PostMapping("/upload")
  public BaseResponse<String> upload(@RequestParam("file") MultipartFile file,
                                          HttpServletRequest request) {
    if (file == null) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR, "未上传文件");
    }
    String s;
    try {
       s = userService.uploadFile(file);
    } catch (Exception e) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR, "上传失败");
    }
    return ResultUtils.success(s);
  }

  /**
   * 根据 id 获取用户（仅管理员）
   *
   * @param id
   * @return
   */
  @GetMapping("/get")
  @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
  public BaseResponse<User> getUserById(long id) {
    if (id <= 0) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR);
    }
    User user = userService.getById(id);
    ThrowUtils.throwIf(user == null, ErrorCode.NOT_FOUND_ERROR);
    return ResultUtils.success(user);
  }

  /**
   * 根据 id 获取包装类
   *
   * @param id
   * @param request
   * @return
   */
  @GetMapping("/get/userVO")
  public BaseResponse<UserVO> getUserVOById(long id, HttpServletRequest request) {
    BaseResponse<User> response = getUserById(id);
    User user = response.getData();
    return ResultUtils.success(userService.getUserVO(user));
  }

  /**
   * 分页获取用户列表（仅管理员）
   *
   * @param userQueryRequest
   * @param request
   * @return
   */
  @PostMapping("/list/page")
  @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
  public BaseResponse<Page<User>> listUserByPage(@RequestBody UserQueryRequest userQueryRequest,
                                                 HttpServletRequest request) {
    long current = userQueryRequest.getCurrent();
    long size = userQueryRequest.getPageSize();
    Page<User> userPage = userService.page(new Page<>(current, size),
            userService.getQueryWrapper(userQueryRequest));
    return ResultUtils.success(userPage);
  }

  /**
   * 分页获取用户封装列表
   *
   * @param userQueryRequest
   * @param request
   * @return
   */
  @PostMapping("/list/page/vo")
  public BaseResponse<Page<UserVO>> listUserVOByPage(@RequestBody UserQueryRequest userQueryRequest,
                                                     HttpServletRequest request) {
    if (userQueryRequest == null) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR);
    }
    long current = userQueryRequest.getCurrent();
    long size = userQueryRequest.getPageSize();
    // 限制爬虫
    ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
    Page<User> userPage = userService.page(new Page<>(current, size),
            userService.getQueryWrapper(userQueryRequest));
    Page<UserVO> userVOPage = new Page<>(current, size, userPage.getTotal());
    List<UserVO> userVO = userService.getUserVO(userPage.getRecords());
    userVOPage.setRecords(userVO);
    return ResultUtils.success(userVOPage);

  }

  @RequestMapping("/test")
  public String test(){
    return "hello,world";
  }
}
